#coding=utf-8
import requests,json,urllib
import re
import pdb
import mysql.connector
import connect_mysql



#引用connect_mysql程序连接数据库
connect_mysql.connect_mysql()


def Input(url, adminname, password,borrow_type, borrowtitle, money, huankuanfangshi, rate, username_type, borrowname,period_type, month, cashgroup, agentname,tender_account_min, pay_type):
    login_headers = {'Referer':url,'Accept-Language':'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
                     'Upgrade-Insecure-Requests':'1','Content-Type':'application/x-www-form-urlencoded',
                     'Accept-Encoding':'gzip, deflate','User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:55.0) Gecko/20100101 Firefox/55.0',
                    'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'}
    first_headers = {'Referer':url+'/bdadd/bdadd_one/','Accept-Language':'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
                     'Upgrade-Insecure-Requests':'1','Content-Type':'application/x-www-form-urlencoded',
                     'Accept-Encoding':'gzip, deflate','User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:55.0) Gecko/20100101 Firefox/55.0',
                    'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'}
    second_headers = {'Referer':url+'/bdadd/userinfo/','Accept-Language':'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
                     'Upgrade-Insecure-Requests':'1','Content-Type':'application/x-www-form-urlencoded',
                     'Accept-Encoding':'gzip, deflate','User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:55.0) Gecko/20100101 Firefox/55.0',
                    'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'}
    thrid_headers = {'Referer':url+'/bdadd/risk/','Accept-Language':'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
                     'Upgrade-Insecure-Requests':'1','Content-Type':'application/x-www-form-urlencoded',
                     'Accept-Encoding':'gzip, deflate','User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:55.0) Gecko/20100101 Firefox/55.0',
                    'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'}
    fouth_headers = {'Referer':url+'/bdadd/bdinfo/','Accept-Language':'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
                     'Upgrade-Insecure-Requests':'1','Content-Type':'application/x-www-form-urlencoded',
                     'Accept-Encoding':'gzip, deflate','User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:55.0) Gecko/20100101 Firefox/55.0',
                    'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'}


        #通过登录接口登录运营后台
    try:
        import time, datetime
        now = time.strftime("%Y%m%d%H%M%S", time.localtime(time.time()))  # 标的编号命名格式,也为业务编号
        time = time.strftime("%Y-%m-%d %H:%M", time.localtime(time.time()))
        userinformation = {'adminname':adminname,'password':password,'authCode':'123456'}
        s = requests.session()
        login = s.post(url, data=userinformation,headers=login_headers,verify=False)
        login1 = str(login)
        if u"登录成功" in login.text:
            print login1 + u"登录成功"
            #登录成功后，进入发标页面
            #第一个页面,borrow_style为还款方式的选择，end为到期还本付息，season为按季付息，
            if username_type == '11':  # 个人借款人
                first = {'post_type':borrow_type,'file_number':now,'borrow_numbers':now,'name':borrowtitle,'username_type':username_type,'username':borrowname,'borrow_use':'1','account':money,
                         'period_type':period_type,'borrow_period':month,'borrow_style':huankuanfangshi,'borrow_apr':rate,'cashgroup':cashgroup,'agent_username':agentname,'pay_type':pay_type}
                firstinput = s.post(url+'/bdadd/bdadd_one/',data=first,cookies=login.cookies,headers=first_headers,verify=False)
                print firstinput.text
                #第二个页面
                #通过正则获取到借款人的详细信息
                borrow = s.get(url+'/bdadd/userinfo/',cookies=login.cookies,headers=second_headers,verify=False)
                username = re.findall(r'name="username"  value="(.+)" borrow_apr=',borrow.text)
                id_number = re.findall(r'name="id_number" value="(.+)" pattern_idnumber=', borrow.text)
                phone1 = re.findall(r'name="phone1" value="(.+)" phonenum=',borrow.text)
                age = re.findall(r'name="age" id="age" value="(.+)" onfocus=',borrow.text)
                #print username
                if username == []:
                    return u'所填信息有误，请仔细检查并重新填入！'
                else:
                    print username[0], id_number[0], phone1[0], age[0]
                    second = {'username': username[0], 'id_number': id_number[0], 'account_use': u'借钱来耍啊！！！',
                              'phone1': phone1[0], 'age': age[0], 'edu': '4', 'marry': '1'}
                    secondinput = s.post(url + '/bdadd/userinfo/', data=second, cookies=login.cookies,
                                         headers=second_headers, verify=False)
                    # print secondinput.text
            #机构借款人
            if username_type == '21':
                # 第一个页面
                first = {'post_type': borrow_type, 'file_number': now, 'borrow_numbers': now, 'name': borrowtitle + now,
                         'username_type': username_type, 'username': borrowname, 'borrow_use': '1', 'account': money,
                         'period_type': period_type,'borrow_period': month, 'borrow_style': huankuanfangshi, 'borrow_apr': rate,
                         'cashgroup': cashgroup, 'agent_username': agentname,'pay_type':pay_type
                         }
                firstinput = s.post(url + '/bdadd/bdadd_one/', data=first, cookies=login.cookies, headers=first_headers,
                                    verify=False)
                # 第二个页面
                borrow = s.get(url + '/bdadd/userinfo/', cookies=login.cookies, headers=second_headers, verify=False)
                username = re.findall(r'<aside>(.*?)</aside>', borrow.text,re.S|re.M)
                print username[0]
                if username == []:
                    return u'所填信息有误，请仔细检查并重新填入！'
                else:
                    second_jigou = {'account_use': '借钱来耍耍！！！'}
                    second_jigou_ = s.post(url + '/bdadd/userinfo/', data=second_jigou, cookies=login.cookies,
                                           headers=second_headers, verify=False)
            #第三个页面
            thrid = {'subtype':'next','property_type':'1'}
            thirdinput = s.post(url+'/bdadd/risk/',data=thrid,cookies=login.cookies,headers=thrid_headers,verify=False)
            #print thirdinput.text
            #第四个页面
            fouth = {'borrow_release_time':time,'is_awart_type':'0','is_mobile_type':'0','award_type':'0','award_status':'2','award_scale':'','borrow_valid_time':'1',
                     'tender_account_min':tender_account_min,'tender_account_max':'0'}
            fouthinput = s.post(url+'/bdadd/bdinfo/',data=fouth,cookies=login.cookies,headers=fouth_headers,verify=False)
            #print fouthinput.text
            print u"业务编号是：" + now + u",发布时间为：" + time
            #在初审页面通过搜索业务编号获取到借款编号
            search_data = {'searchType':'borrow_numbers','searchWord':now}
            search = s.get(url+'/bdverify/index/',params=search_data,cookies=login.cookies,headers=login_headers,verify=False)
            res_td = r'<td>(.*?)</td>'
            borrowid0 = re.findall(res_td, search.text, re.S | re.M)
            borrowid = int(borrowid0[0])
            #borrowid = mysql_connect.research(now)
            print u"借款编号是：" + str(borrowid)
            #通过正则取出进入一审的url中的id
            examineid0 = re.findall(r'/bdverify/verifyone/\?id=(.+)',search.text)
            examineid1 = examineid0[0]
            examineid = examineid1[0:8]
            #examineid = mysql_connect.researchid(now)
            print examineid
            #进入一审
            examine01_data = {'id':examineid,'borrow_nid':borrowid}
            examine01 = s.get(url+'/bdverify/verifyone/',params=examine01_data,cookies=login.cookies,headers=login_headers,verify=False)
            examine01_post_data = {'borrow_status_small':'3','remark':u'审核通过'}
            examine01_post = s.post(examine01.url,data=examine01_post_data,cookies=login.cookies,headers=login_headers,verify=False)
            #提交二审
            #pdb.set_trace()   #断点
            examine02_url = url+'/bdverify/subtwo/?id='+ str(examineid) +'&borrow_nid='+ str(borrowid)
            examine02_post_data = {'is_awart_type':'0','is_mobile_type':'0','award_type':'0','award_status':'2','award_scale':'','borrow_valid_time':'1','borrow_release_time':time,
                                   'tender_account_min':tender_account_min,'tender_account_max':'0'}
            examine02_post= s.post(examine02_url,data=examine02_post_data,cookies=login.cookies,headers=login_headers,verify=False)
            #二审通过
            examine03_url = url+'/bdverify/verifytwo/?id=' + str(examineid) + '&borrow_nid=' + str(borrowid)
            examine03_post_data = {'borrow_status_small':'7','remark':u'审核通过'}
            examine03_post = s.post(examine03_url, data=examine03_post_data, cookies=login.cookies, headers=login_headers,verify=False)
            #进行出队列
            if url == 'http://op.yipaiwang.co':
                out = s.get('http://task.yipaiwang.co/worthautoissue.task.php')
                print out.text
            if url == 'http://op.yipaiwang.cc':
                out = s.get('http://task.yipaiwang.cc/worthautoissue.task.php')
                print out.text
            if url == 'http://op.yidai.xyz':
                out = s.get('http://task.yidai.xyz/worthautoissue.task.php')
                print out.text

        else:
            return  u"登录失败,请确认账号和密码是否匹配"
        # 进行数据库写入
        connect = connect_mysql.connect_mysql()[0]   #connect是由connect_mysql函数返回的第一个值
        cursor = connect.cursor()
        # SQL 插入语句
        sql = "insert into mysql.edai_borrow(url,username,agent_username,borrowname,post_type,amount_type,account,borrow_nid,borrow_style,borrow_period,borrow_apr,tender_account_min,borrow_username,modify_time,borrow_numbers) values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')" % (url,borrowname, agentname, borrowtitle, borrow_type, borrow_type, money, borrowid, huankuanfangshi, month, rate,tender_account_min, borrowname, time, now)
        print sql
        # 执行sql语句
        input = cursor.execute(sql)
        connect.commit()  # 实例提交命令
        #cursor.close()
        #connect.close()
        print("insert ok")
        return u"借款标题是：" + borrowtitle + str(borrowid) + u",借款人是：" + borrowname + u"，借款编号是：" + str(borrowid)


    except:
        return u"请仔细检查所填内容并再次尝试!"